from tortoise.models import Model
from tortoise import fields
from typing import Optional
from datetime import datetime


class User(Model):
    """
    用户表模型
    """
    user_id = fields.BigIntField(pk=True, description="用户ID")
    dept_id = fields.BigIntField(description="部门ID")
    user_name = fields.CharField(max_length=30, null=False, description="用户账号")
    nick_name = fields.CharField(max_length=30, null=False, description="用户昵称")
    user_type = fields.CharField(max_length=2, description="用户类型 (00系统用户)")
    email = fields.CharField(max_length=50, null=True, description="用户邮箱")
    phonenumber = fields.CharField(max_length=11, null=True, description="手机号码")
    sex = fields.CharField(max_length=1, null=True, description="用户性别 (0男 1女 2未知)")
    avatar = fields.CharField(max_length=100, null=True, description="头像地址")
    password = fields.CharField(max_length=100, null=True, description="密码")
    status = fields.CharField(max_length=1, null=True, description="账号状态 (0正常 1停用)")
    del_flag = fields.CharField(max_length=1, null=True, description="删除标志 (0代表存在 2代表删除)")
    login_ip = fields.CharField(max_length=128, null=True, description="最后登录IP")
    login_date = fields.DatetimeField(null=True, description="最后登录时间")
    pwd_update_date = fields.DatetimeField(null=True, description="密码最后更新时间")
    create_by = fields.CharField(max_length=64, null=True, description="创建者")
    create_time = fields.DatetimeField(null=True, description="创建时间")
    update_by = fields.CharField(max_length=64, null=True, description="更新者")
    update_time = fields.DatetimeField(null=True, description="更新时间")
    remark = fields.CharField(max_length=500, null=True, description="备注")

    class Meta:
        table = "sys_user"  # 指定实际的数据库表名
        table_description = "用户信息表"

    def __str__(self):
        return f"User(user_id={self.user_id}, user_name={self.user_name})"

    @property
    def is_active(self) -> bool:
        """判断用户是否激活"""
        return self.status == "0"

    @property
    def is_deleted(self) -> bool:
        """判断用户是否被删除"""
        return self.del_flag == "2"

    def get_sex_display(self) -> str:
        """获取性别显示名称"""
        sex_map = {"0": "男", "1": "女", "2": "未知"}
        return sex_map.get(self.sex, "未知")

    def get_status_display(self) -> str:
        """获取状态显示名称"""
        status_map = {"0": "正常", "1": "停用"}
        return status_map.get(self.status, "未知")

    @classmethod
    async def get_active_users(cls):
        """获取所有激活的用户"""
        return await cls.filter(status="0", del_flag__not="2")

    @classmethod
    async def get_by_username(cls, username: str):
        """根据用户名获取用户"""
        return await cls.filter(user_name=username, del_flag__not="2").first()

    @classmethod
    async def get_by_email(cls, email: str):
        """根据邮箱获取用户"""
        return await cls.filter(email=email, del_flag__not="2").first()

    async def soft_delete(self):
        """软删除用户"""
        self.del_flag = "2"
        self.update_time = datetime.now()
        await self.save(update_fields=["del_flag", "update_time"])

    async def activate(self):
        """激活用户"""
        self.status = "0"
        self.update_time = datetime.now()
        await self.save(update_fields=["status", "update_time"])

    async def deactivate(self):
        """停用用户"""
        self.status = "1"
        self.update_time = datetime.now()
        await self.save(update_fields=["status", "update_time"])